'use strict';

import React, {Component, PropTypes} from 'react';

export default class Pagination extends Component {
	/*
	 * 构造函数。
	 *
	 * @param props 只读属性
	 */
	constructor(props) {
		super(props);
		this.state = {
			currentPage: 1,
		};
	}

	/*
	 * 初始化。
	 */
	init() {
		this.setState({
			currentPage: 1,
		});
	}

	/*
	 * 计算页数。
	 */
	calculatePage() {
		let totalPage = this.props.total / this.props.pageSize;
		totalPage = parseInt(totalPage) === totalPage ? parseInt(totalPage) : parseInt(totalPage) + 1;
		
		if (totalPage === 0) {
			totalPage++;
		}
		
		return totalPage;
	}

	/*
	 * 上一页。
	 * @param e 事件
	 */
	handlePreviousClick(e) {
		e.preventDefault();

		let currentPage = this.state.currentPage;
		if (currentPage !== 1) {
			currentPage--;
			this.setState({
				currentPage: currentPage,
			});
			this.props.onSelect(currentPage);
		}
	}

	/*
	 * 下一页。
	 * @param e 事件
	 */
	handleNextClick(e) {
		e.preventDefault();

		let currentPage = this.state.currentPage;
		let totalPage = this.calculatePage();
		if (currentPage !== totalPage) {
			currentPage++;
			this.setState({
				currentPage: currentPage,
			});
			this.props.onSelect(currentPage);
		}
	}

	/*
	 * 渲染视图。
	 *
	 * @return 视图
	 */
	render() {
		let totalPage = this.calculatePage();
		let currentPage = this.state.currentPage;
		return (
			<div
				className={this.props.className}
				style={this.props.style}
			>
				<a
					type="button"
					className="am-btn am-btn-link"
					style={{
						backgroundColor: '#ffffff',
						border: '1px solid #cccccc',
					}}
					onClick={this.handlePreviousClick.bind(this)}
					disabled={currentPage === 1 ? true : false}
				>‹</a>
				<span
					style={{
						display: 'inline-block',
						lineHeight: '35px',
						padding: '0 10px',
						backgroundColor: '#fafafa',
						borderTop: '1px solid #cccccc',
						borderBottom: '1px solid #cccccc',
						verticalAlign: 'bottom',
					}}
				>{currentPage + '/' + totalPage}</span>
				<a
					type="button"
					className="am-btn am-btn-link"
					style={{
						backgroundColor: '#ffffff',
						border: '1px solid #cccccc',
					}}
					onClick={this.handleNextClick.bind(this)}
					disabled={currentPage === totalPage ? true : false}
				>›</a>
			</div>
		);
	}
}

Pagination.propTypes = {
	total: PropTypes.number,
	pageSize: PropTypes.number,
	center: PropTypes.bool,
	right: PropTypes.bool,
	onSelect: PropTypes.func,
	style: PropTypes.object,
	className: PropTypes.string,
};
Pagination.defaultProps = {
	total: 0,
	pageSize: 10,
	onSelect: link => {},
};
